# oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/multiverse-neon.omp.json" | Invoke-Expression
#oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/blue-owl.omp.json" | Invoke-Expression
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/paradox.omp.json" | Invoke-Expression

function localforward {
        ssh -L 5000:127.0.0.1:5000 root@119.3.163.162 -N
    }

function e-PG {
    Write-Host "located to Proj Ground..." -ForegroundColor Green
    Write-Host ""
    Write-Host ""
    cd 'D:\BaiduSyncdisk\oP\PG\'
}

# Locate
New-Alias -Name loc -Value Set-Location
New-Alias -Name e -Value Set-Location
New-Alias -Name c -Value md

function c-df {
    param (
        [string]$path
    )
    if (Test-Path $path) {
        # Update the last write time if the file exists
        (Get-Item $path).LastWriteTime = Get-Date
    } else {
        # Create the file if it does not exist
        New-Item -ItemType File -Path $path
    }
}


function i {
    Get-ChildItem | Format-List -Property Name, Length, LastWriteTime, Attributes
}

function y {
    [char]::ConvertFromUtf32(0x1F4C4).ToString()
    $filePath = Read-Host "Please enter the file path to view:"
    Get-Content $filePath
}

function y-me {
    type README.md
}


function git-stag {
    git diff --staged --name-only
}

function s-pshe {
    code $PROFILE
}

function s-zshe {
    Write-Host "Opening PowerShell" -ForegroundColor Green
    Start-Process -FilePath "powershell.exe" -ArgumentList "-NoExit"
}

function s-host {
    code $env:windir\System32\drivers\etc\hosts
}

function l-path {
    $env:PATH -split ';'
}


function i-XO {
    msinfo32
}

## -------------------------------------------------------------------- NPM操作
function hel-npma {
    Write-Host "Listing npm helps..." -ForegroundColor Blue
    Write-Host{"l-proj_npm - List npm proj dependencies"} -ForegroundColor Darkblue
    Write-Host{"t-proj_npm - Run npm test"} -ForegroundColor Darkblue
    Write-Host{"y-proj_npm - List npm proj current status"} -ForegroundColor Darkblue
    Write-Host{"b-proj_npm - Run npm build"} -ForegroundColor Darkblue
    Write-Host{"s-npma - Open .npmrc file"} -ForegroundColor Darkblue
    Write-Host{"u-npma - Update npm dependencies"} -ForegroundColor Darkblue
    Write-Host{""}-ForegroundColor Darkblue
    Write-Host{"sta-proj_npm - Start npm start script"} -ForegroundColor Darkblue
    Write-Host{"aud-pack - Run npm audit"} -ForegroundColor Darkblue
    Write-Host{"fix-pack - Run npm audit fix"} -ForegroundColor Darkblue
    Write-Host{"ins-pack - Install npm dependencies"} -ForegroundColor Darkblue
    Write-Host{"ins-pack-deve - Install npm dev dependencies"} -ForegroundColor Darkblue
    Write-Host{""}-ForegroundColor Darkblue
}

function i-conf_npma {
     [char]::ConvertFromUtf32(0x2699).ToString()
     Write-Host "Listing NPM config..." -ForegroundColor Darkblue
    npm config list
}

function y-proj.npm {
    Write-Host "Showing current status of proj.npm..." -ForegroundColor Green
    if (Test-Path -Path.\package.json) {
    Write-Host "Package.json content:" -ForegroundColor Darkgreen

    Get-Content -Path .\package.json
    } else {
    Write-Host "No package.json found in current directory." -ForegroundColor Red
    }
}

function l-pack {
     Write-Host "List of proj pack dependencies...." -ForegroundColor Darkgreen
     Write-Host ""
     Write-Host ""
    npm list
}

function t-proj_npm {
    Write-Host "Running npm test..." -ForegroundColor Darkblue
    npm test
}

function b-proj_npm {
    Write-Host "Running npm build..." -ForegroundColor Darkblue
    npm run build
}

function s-npma {
    code "C:\Users\morge\.npmrc"
}

function u-proj_npm {
    npm update
    ncu -u
}

function sta-proj_npm {
    npm start
}

function aud-proj_npm {
    npm audit
}

function fix-proj_npm {
    npm audit fix
}

function ins-pack {
    npm ci
}

function uni-pack {
    npm uninstall
}

function ins-pack_dev {
    npm install --save-dev
}

function pac-proj_npm {
    npm pack
}

function pub-proj_npm {
    npm publish
}

function ded-pack {
    npm dedupe
}

function out-pack {
    npm outdated
}

function z-cach_npma {
    npm cache clean --force
}

## - SSH操作

function s-sshe{
    code $env:USERPROFILE\.ssh\config
}

## -------------------------------------------------------------------- 基础操作
function l{
    dir
}

function z {
   cls
}



## -------------------------------------------------------------------- 通过对话获得文件目录作为参数，删除整个目录
function d-dd {
    Write-Host "Deleting directory..." -ForegroundColor Blue
    [char]::ConvertFromUtf32(0x1F4C2).ToString()
    
    $dire = Read-Host "Enter the directory path to delete"
    if (Test-Path $dire) {
        Remove-Item -Path $dire -Recurse -Force
    } else {
        Write-Host "Directory not found." -ForegroundColor Red
    }

    Write-Host ""
    [char]::ConvertFromUtf32(0x267B).ToString()
    Write-Host "The directory assigned deleted." -ForegroundColor Green
}

# 接收一个展开层数的参数，默认为1。根据该参数以树状形式展开显示当前目录下的所有文件和目录。
function y-dT {
    # Force UTF-8 encoding

    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

    # Unicode characters for tree structure
    $corner = [char]0x2514
    $tee = [char]0x251C
    $vertical = [char]0x2502
    $horizontal = [char]0x2500

    # Ask the user for the number of levels to expand
    [char]::ConvertFromUtf32(0x1F384).ToString()
    $L = Read-Host "Enter the number of directory levels to expand (default is 1)"

    # If the user didn't input anything, use the default value of 1
    if ([string]::IsNullOrWhiteSpace($L)) {
        $L = 1
    }
    else {
        # Ensure the input is a valid integer
        try {
            $L = [int]$L
        }
        catch {
            Write-Host "Invalid input. Using default value of 1."
            $L = 1
        }
    }

    $currentPath = Get-Location
    $items = Get-ChildItem -Path $currentPath -Depth $L

    Write-Host "Directory tree of: $currentPath"
    Write-Host "$corner$($horizontal.ToString() * 2)$($currentPath.Name)"

    function Write-TreeItem {
        param (
            [string]$Name,
            [int]$CurrentLevel,
            [bool]$IsLast,
            [string]$Prefix = ""
        )

        $indent = "$Prefix"
        $branch = if ($IsLast) { "$corner$($horizontal.ToString() * 2)" } else { "$tee$($horizontal.ToString() * 2)" }
        $branchIndent = if ($IsLast) { "    " } else { "$vertical   " }

        Write-Host "$indent$branch$Name"
        return "$indent$branchIndent"
    }

    function Show-SubTree {
        param (
            [System.IO.FileSystemInfo]$Item,
            [int]$CurrentLevel,
            [string]$Prefix
        )

        $subItems = Get-ChildItem -Path $Item.FullName -Depth 0
        $subItemCount = $subItems.Count
        $processedSubItems = 0

        foreach ($subItem in $subItems) {
            $processedSubItems++
            $isLastSubItem = ($processedSubItems -eq $subItemCount)
            $newPrefix = Write-TreeItem -Name $subItem.Name -CurrentLevel $CurrentLevel -IsLast $isLastSubItem -Prefix $Prefix

            if ($subItem.PSIsContainer -and $CurrentLevel -lt $L) {
                Show-SubTree -Item $subItem -CurrentLevel ($CurrentLevel + 1) -Prefix $newPrefix
            }
        }
    }

    $rootItems = Get-ChildItem -Path $currentPath -Depth 0
    $rootItemCount = $rootItems.Count
    $processedRootItems = 0

    foreach ($item in $rootItems) {
        $processedRootItems++
        $isLast = ($processedRootItems -eq $rootItemCount)
        $prefix = Write-TreeItem -Name $item.Name -CurrentLevel 0 -IsLast $isLast

        if ($item.PSIsContainer -and $L -gt 1) {
            Show-SubTree -Item $item -CurrentLevel 1 -Prefix $prefix
        }
    }
}

## -------------------------------------------------------------------- NPM

function y-dT_npm {
    [char]::ConvertFromUtf32(0x1F384).ToString()
    Read-Host "Enter the directory depth to list (default is 1):"
    npm list --depth=1
}

function ini-proj.npm {
    npm init
}

function ini-proj.git {
    git init
}

function ini-proj.tsc {
    tsc --init
}

function ini-proj.react {
    npm ci --save-dev typescript @types/react @types/react-dom
}

function std-proj_ot_react {
    git init
    npm init -y
    npm install --save-dev typescript @types/react @types/react-dom
    npm install --save-dev @testing-library/jest-dom @testing-library/react @testing-library/user-event
    npm install --save-dev @types/jest ts-jest @types/node
    npm install --save-dev @testing-library/dom
    tsc --init
}

## -------------------------------------------------------------------- create-react-app with TypeScript

function c-react {
    $projectName = Read-Host -Prompt "React Proj Name"
    $template = Read-Host -Prompt "React Template (Default: typescript)"

    if ([string]::IsNullOrWhiteSpace($projectName)) {
        Write-Host "Error: Project Name is required." -ForegroundColor Red
        return
    }

    if ([string]::IsNullOrWhiteSpace($template)) {
        $template = "typescript"
    }

    Write-Host "Building React Proj '$projectName' with template '$template'..." -ForegroundColor Yellow

    # 使用 Start-Process 运行 npm create 命令
    $createProcess = Start-Process -FilePath "npx.cmd" -ArgumentList "create-react-app", $projectName, "--template", $template -NoNewWindow -PassThru -Wait
    if ($createProcess.ExitCode -ne 0) {
        Write-Host "Failed to create project. Exit code: $($createProcess.ExitCode)" -ForegroundColor Red
        return
    }

    Set-Location $projectName

    Write-Host "Installing dependencies..." -ForegroundColor Yellow
    $installProcess = Start-Process -FilePath "npm.cmd" -ArgumentList "install" -NoNewWindow -PassThru -Wait
    if ($installProcess.ExitCode -ne 0) {
        Write-Host "Failed to install dependencies. Exit code: $($installProcess.ExitCode)" -ForegroundColor Red
        return
    }
}

function c-tsc {
    Write-Host "Creating tsconfig.json..." -ForegroundColor Blue
    npx tsc --init
}




## ---------------------------------------------------------- 标准初始化 Vite

function std-vite {
    $projectName = Read-Host -Prompt "React Proj Name"

    if ([string]::IsNullOrWhiteSpace($projectName)) {
        Write-Host "Error: Project Name is required." -ForegroundColor Red
        return
    }

    Write-Host "Building React Proj '$projectName'..." -ForegroundColor Yellow

    # 使用 Start-Process 运行 npm create 命令
    $createProcess = Start-Process -FilePath "npm.cmd" -ArgumentList "create", "vite@latest", $projectName, "--", "--template", "react" -NoNewWindow -PassThru -Wait
    if ($createProcess.ExitCode -ne 0) {
        Write-Host "Failed to create project. Exit code: $($createProcess.ExitCode)" -ForegroundColor Red
        return
    }

    Set-Location $projectName

    Write-Host "Installing dependencies..." -ForegroundColor Yellow
    $installProcess = Start-Process -FilePath "npm.cmd" -ArgumentList "install" -NoNewWindow -PassThru -Wait
    if ($installProcess.ExitCode -ne 0) {
        Write-Host "Failed to install dependencies. Exit code: $($installProcess.ExitCode)" -ForegroundColor Red
        return
    }

    Write-Host "Starting dev server..." -ForegroundColor Green
    Start-Process -FilePath "npm.cmd" -ArgumentList "run", "dev" -NoNewWindow
}


#-----------------------------------------自检


function che-envi {
    Write-Host "Auditing environment..." -ForegroundColor Blue
    # 检查是否安装了node
    $nodeVersion = node -v
    if ([string]::IsNullOrWhiteSpace($nodeVersion)) {
        Write-Host "Node.js is not installed." -ForegroundColor Red
        return
    }
    Write-Host "Node.js version: $nodeVersion" -ForegroundColor Green

    # 检查是否安装了npm
    $npmVersion = npm -v
    if ([string]::IsNullOrWhiteSpace($npmVersion)) {
        Write-Host "npm is not installed." -ForegroundColor Red
        return
    }
    Write-Host "NPM version: $npmVersion" -ForegroundColor Green

    # 检查是否安装了git
    $gitVersion = git --version
    if ([string]::IsNullOrWhiteSpace($gitVersion)) {
        Write-Host "Git is not installed." -ForegroundColor Red
        return
    }
    Write-Host "Git version: $gitVersion" -ForegroundColor Green

}

##-------------------------ssh

function p-Cu {
    Write-Host "The Public Key is ..." -ForegroundColor Darkblue    
    Get-Content $env:USERPROFILE\.ssh\id_rsa.pub    
}


##--------------------------git

function i-conf_git {
    git config --list
}